using System.Collections;
using UnityEngine;
using UnityEngine.SceneManagement;

public class GameInit : MonoBehaviour
{
    private static GameInit instance;
    public static GameInit Instance
    {
        get
        {
            if (instance == null)
            {
                var go = new GameObject("GameInit");
                instance = go.AddComponent<GameInit>();
                DontDestroyOnLoad(go);
            }
            return instance;
        }
    }

    void Awake()
    {
        if (instance != null && instance != this)
        {
            Destroy(gameObject);
            return;
        }
        instance = this;
        DontDestroyOnLoad(gameObject);

        // 在Awake中就设置分辨率
        SetInitialResolution();
    }

    // Start is called before the first frame update
    void Start()
    {
        GlobalData.Initialize();
        
        // 监听场景加载事件
        SceneManager.sceneLoaded += OnSceneLoaded;
    }

    private void SetInitialResolution()
    {
        // 目标分辨率
        float targetWidth = 1080f;
        float targetHeight = 1920f;
        float targetAspect = targetWidth / targetHeight;

        // 获取当前屏幕分辨率
        float screenWidth = Screen.currentResolution.width;
        float screenHeight = Screen.currentResolution.height;

        // 计算新的分辨率，优先保证高度
        int newWidth, newHeight;
        
        // 如果屏幕高度小于目标高度，按比例缩小
        if (screenHeight < targetHeight)
        {
            float scale = screenHeight / targetHeight;
            newHeight = (int)screenHeight;
            newWidth = (int)(targetWidth * scale);
        }
        else
        {
            // 如果屏幕高度足够，以高度为基准计算宽度
            newHeight = (int)targetHeight;
            newWidth = (int)(targetHeight * targetAspect);
        }

        // 强制设置全屏模式
        Screen.fullScreenMode = FullScreenMode.Windowed;
        Screen.SetResolution(newWidth, newHeight, false);

        // 设置Canvas Scaler
        StartCoroutine(SetupCanvasScalers());

        Debug.Log($"初始分辨率设置: {newWidth}x{newHeight}, 缩放比例: {newHeight/targetHeight:F2}");
    }

    private IEnumerator SetupCanvasScalers()
    {
        // 等待一帧，确保所有Canvas都已加载
        yield return null;

        var canvasScalers = FindObjectsOfType<UnityEngine.UI.CanvasScaler>();
        foreach (var canvasScaler in canvasScalers)
        {
            canvasScaler.uiScaleMode = UnityEngine.UI.CanvasScaler.ScaleMode.ScaleWithScreenSize;
            canvasScaler.referenceResolution = new Vector2(1080f, 1920f);
            canvasScaler.matchWidthOrHeight = 0.5f;
        }
    }

    private void OnSceneLoaded(Scene scene, LoadSceneMode mode)
    {
        // 场景加载后重新设置Canvas Scaler
        StartCoroutine(SetupCanvasScalers());
    }

    void OnApplicationFocus(bool focus)
    {
        if (focus)
        {
            // 当应用获得焦点时重新设置分辨率
            SetInitialResolution();
        }
    }

    void OnDestroy()
    {
        // 移除场景加载事件监听
        SceneManager.sceneLoaded -= OnSceneLoaded;
    }
}
